﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CubicFWNet.Application.SystemManager;
using CubicFWNet.Common;
using CubicFWNet.Data.Models;
using CubicFWNet.Data.ViewModal;
using CubicFWNet.Mvc.Models;
using PagedList;

namespace CubicFWNet.Mvc.Controllers
{
    public class PurchaseController : ControllerBase
    {
        private OriginalCostApp _originalCostApp;
        private TechnologyApp _technologyApp;
        private OperateRecordApp _operateRecordApp;
        private OrderProductApp _orderProductApp;
        private FinanceCostApp _financeCostApp;
        private PurchaseApp _purchaseApp;
        private ExamineApp _examineApp;
        private ProductApp _productApp;
        private WorksheetApp _worksheetApp;
        private OrderApp _orderApp;
        private CustomerApp _customerApp;
        private MaterialFormatApp _inventoryFormatApp;
        private ArapApp _arapApp;
        private CreateNewNumberApp _createNewNumberApp;
        private InvoiceApp _invoiceApp;

        public PurchaseController()
        {
            _originalCostApp = new OriginalCostApp();
            _technologyApp = new TechnologyApp();
            _operateRecordApp = new OperateRecordApp();
            _orderProductApp = new OrderProductApp();
            _financeCostApp = new FinanceCostApp();
            _purchaseApp = new PurchaseApp();
            _examineApp = new ExamineApp();
            _productApp = new ProductApp();
            _orderApp = new OrderApp();
            _customerApp = new CustomerApp();
            _worksheetApp = new WorksheetApp();
            _inventoryFormatApp = new MaterialFormatApp();
            _arapApp = new ArapApp();
            _createNewNumberApp = new CreateNewNumberApp();
            _invoiceApp = new InvoiceApp();
        }

        // GET: Purchase
        public ActionResult Index(Guid orderId)
        {
            //Guid orderId = new Guid("B94AC89C-6D21-47C0-9F7D-B34D873BB571");
            Order order = _orderApp.GetInfo(orderId);
            Customer customer = _customerApp.GetInfo(order.CustomeId.Value);
            IQueryable<ProductTechnologyView> proList = _productApp.GetProductListByOrderId(order.Id);

            ViewBag.ProList = proList;

            ViewBag.CustomerShortName = customer.ShortName;

            ViewBag.GenerateNum = GenerateId.GenerateOrderNumber();//生成发货单号
            ViewBag.OperationName = operatorModel.FamilyName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间
            return View(order);
        }


        public ActionResult PurchaseCompose(int page = 1, string creatorName = "", string productName = "", string beginTime = "", string endTime = "")
        {
            ViewBag.creatorName = creatorName.Trim();
            ViewBag.productName = productName.Trim();
            DateTime _beginTime = DateTime.Parse("2000-01-01 10:10:10");
            DateTime _endTime = DateTime.Now.Date.AddDays(1);
            ViewBag.beginTime = "";
            ViewBag.endTime = "";
            if (!string.IsNullOrEmpty(beginTime) && Validate.IsDate(beginTime))
            {
                _beginTime = DateTime.Parse(beginTime.Trim());
                ViewBag.beginTime = beginTime.Trim();
            }
            if (!string.IsNullOrEmpty(endTime) && Validate.IsDate(endTime))
            {
                _endTime = DateTime.Parse(endTime.Trim());
                ViewBag.endTime = endTime.Trim();
            }
            IPagedList<ProductTechnologyView> tecjList = _purchaseApp.GetList(-11, -10, creatorName, productName, _beginTime, _endTime).ToPagedList(page, 10);

            return View(tecjList);
        }


        public ActionResult PurchaseIsOkQuery(int page = 1, string creatorName = "", string productName = "", string beginTime = "", string endTime = "")
        {
            ViewBag.creatorName = creatorName.Trim();
            ViewBag.productName = productName.Trim();
            DateTime _beginTime = DateTime.Parse("2000-01-01 10:10:10");
            DateTime _endTime = DateTime.Now.Date.AddDays(1);
            ViewBag.beginTime = "";
            ViewBag.endTime = "";
            if (!string.IsNullOrEmpty(beginTime) && Validate.IsDate(beginTime))
            {
                _beginTime = DateTime.Parse(beginTime.Trim());
                ViewBag.beginTime = beginTime.Trim();
            }
            if (!string.IsNullOrEmpty(endTime) && Validate.IsDate(endTime))
            {
                _endTime = DateTime.Parse(endTime.Trim());
                ViewBag.endTime = endTime.Trim();
            }
            IPagedList<ProductTechnologyView> tecjList = _purchaseApp.GetList(-20, -10, creatorName, productName, _beginTime, _endTime).ToPagedList(page, 10);

            return View(tecjList);
        }

        public ActionResult PurchaseQuery(int page = 1, string creatorName = "", string productName = "", string beginTime = "", string endTime = "")
        {
            ViewBag.creatorName = creatorName.Trim();
            ViewBag.productName = productName.Trim();
            DateTime _beginTime = DateTime.Parse("2000-01-01 10:10:10");
            DateTime _endTime = DateTime.Now.Date.AddDays(1);
            ViewBag.beginTime = "";
            ViewBag.endTime = "";
            if (!string.IsNullOrEmpty(beginTime) && Validate.IsDate(beginTime))
            {
                _beginTime = DateTime.Parse(beginTime.Trim());
                ViewBag.beginTime = beginTime.Trim();
            }
            if (!string.IsNullOrEmpty(endTime) && Validate.IsDate(endTime))
            {
                _endTime = DateTime.Parse(endTime.Trim());
                ViewBag.endTime = endTime.Trim();
            }
            IPagedList<ProductTechnologyView> tecjList = _purchaseApp.GetList(1, -10, creatorName, productName, _beginTime, _endTime).ToPagedList(page, 10);

            return View(tecjList);
        }

        public ActionResult PurQuery(int page = 1, string creatorName = "", string productName = "", string beginTime = "", string endTime = "")
        {
            ViewBag.creatorName = creatorName.Trim();
            ViewBag.productName = productName.Trim();
            DateTime _beginTime = DateTime.Parse("2000-01-01 10:10:10");
            DateTime _endTime = DateTime.Now.Date.AddDays(1);
            ViewBag.beginTime = "";
            ViewBag.endTime = "";
            if (!string.IsNullOrEmpty(beginTime) && Validate.IsDate(beginTime))
            {
                _beginTime = DateTime.Parse(beginTime.Trim());
                ViewBag.beginTime = beginTime.Trim();
            }
            if (!string.IsNullOrEmpty(endTime) && Validate.IsDate(endTime))
            {
                _endTime = DateTime.Parse(endTime.Trim());
                ViewBag.endTime = endTime.Trim();
            }
            IPagedList<ProductTechnologyView> tecjList = _purchaseApp.GetPurList(1, -10, creatorName, productName, _beginTime, _endTime).ToPagedList(page, 10);

            return View(tecjList);
        }


        public ActionResult PurQueryOk(int page = 1, string creatorName = "", string productName = "", string beginTime = "", string endTime = "")
        {
            ViewBag.creatorName = creatorName.Trim();
            ViewBag.productName = productName.Trim();
            DateTime _beginTime = DateTime.Parse("2000-01-01 10:10:10");
            DateTime _endTime = DateTime.Now.Date.AddDays(1);
            ViewBag.beginTime = "";
            ViewBag.endTime = "";
            if (!string.IsNullOrEmpty(beginTime) && Validate.IsDate(beginTime))
            {
                _beginTime = DateTime.Parse(beginTime.Trim());
                ViewBag.beginTime = beginTime.Trim();
            }
            if (!string.IsNullOrEmpty(endTime) && Validate.IsDate(endTime))
            {
                _endTime = DateTime.Parse(endTime.Trim());
                ViewBag.endTime = endTime.Trim();
            }
            IPagedList<ProductTechnologyView> tecjList = _purchaseApp.GetPurList(10, -10, creatorName, productName, _beginTime, _endTime).ToPagedList(page, 10);

            return View(tecjList);
        }


        public ActionResult Reconciliation(int page = 1, string financeNumber = "", string productName = "", string supplierName = "")
        {
            ViewBag.financeNumber = financeNumber.Trim();
            ViewBag.productName = productName.Trim();
            ViewBag.SupplierName = supplierName.Trim();
            IPagedList<ReconciliationView> rvList = _purchaseApp.GetListReconciliation(-1, financeNumber.Trim(), productName.Trim(), supplierName.Trim()).ToPagedList(page, 10);
            return View(rvList);
        }

        public ActionResult CompleteReconc(int page = 1, string financeNumber = "", string productName = "", string supplierName = "")
        {
            ViewBag.financeNumber = financeNumber.Trim();
            ViewBag.productName = productName.Trim();
            ViewBag.SupplierName = supplierName.Trim();
            IPagedList<ReconciliationView> rvList = _purchaseApp.GetListReconciliation(1, financeNumber.Trim(), productName.Trim(), supplierName.Trim()).ToPagedList(page, 10);
            return View(rvList);
        }

        public ActionResult YingFuQuery(int page = 1, string customerName = "", string financeNumber = "")
        {
            ViewBag.CustomerName = customerName.Trim();
            ViewBag.FinanceNumber = financeNumber.Trim();
            IPagedList<ArapView> arapList = _arapApp.GetListArapYingfuViews(2, -10, customerName.Trim(), financeNumber.Trim()).ToPagedList(page, 10);
            return View(arapList);
        }

        public ActionResult YingFuInfo(string financeNumber)
        {
            ViewBag.OperationName = operatorModel.FamilyName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间
            List<Arap> arapList = _arapApp.GetListArapByName(financeNumber);
            List<ArapView> list = new List<ArapView>();
            foreach (var item in arapList)
            {
                ArapView web = _arapApp.GetSingleArapView(item.Id);
                if (web != null)
                {
                    list.Add(web);
                }
            }
            ViewBag.FinanceNumber = financeNumber;
            return View(list);
        }

        public ActionResult AddSendCard()
        {
            ViewBag.OperationName = operatorModel.FamilyName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间
            return View();
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string InsertSendCard(SendCar sc)
        {
            sc.InvoicId = Guid.NewGuid();
            sc.Id = Guid.NewGuid();
            sc.Type = 1;
            sc.SendType = 1;
            sc.Status = 0;
            sc.PayType = 1;
            if (sc.CreateTime == null || sc.CreateTime == DateTime.MinValue)
            {
                sc.CreateTime = DateTime.Now;
            }
            sc.CreatorId = operatorModel.UserId;
            sc.CreatorName = operatorModel.FamilyName;
            _invoiceApp.AddSendCar(sc);
            return Result.ToJson();
        }

        public ActionResult ReconciliationInfo(Guid id)
        {
            ReconciliationView web = _purchaseApp.GetSingleReconciliation(id);
            ViewBag.OperationName = operatorModel.FamilyName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间
            ViewBag.TotalMoney = (web.Amount * web.CostPrice).ToString("f2");
            return View(web);
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string UpdatePuraseInfo(PurchaseCompose web)
        {
            PurchaseCompose pc = _purchaseApp.GetSinglePurchaseComposeById(web.Id);
            pc.SupplierId = web.SupplierId;
            pc.CostPrice = web.CostPrice;
            int a = _purchaseApp.UpdatePurchaseCompose(pc);//修改采购单状态
            if (a == 1)
            {
                return new { Code = 200 }.ToJson();
            }
            else
            {
                return new { Code = -200 }.ToJson();
            }
        }


        [HttpPost]
        [HandlerAjaxOnly]
        public string UpdatePurasePrice(PurchaseCompose web)
        {
            PurchaseCompose pc = _purchaseApp.GetSinglePurchaseComposeById(web.Id);
            pc.CostPrice = web.CostPrice;
            int a = _purchaseApp.UpdatePurchaseCompose(pc);//修改采购单状态
            if (a == 1)
            {
                var ppSubtemp = _purchaseApp.GetSinglePurchasePrintSubByother(web.ProductId, pc.Id);
                if (ppSubtemp != null)
                {
                    ppSubtemp.CostPrice = web.CostPrice;
                    _purchaseApp.UpdatePurchasePrintSub(ppSubtemp);
                }
                return new { Code = 200 }.ToJson();
            }
            else
            {
                return new { Code = -200 }.ToJson();
            }
        }

        /// <summary>
        /// 采购修改发票号
        /// </summary>
        /// <param name="id"></param>
        /// <param name="financeNumber"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        public string UpdateReconciliationAjax(Guid id, string financeNumber)
        {
            //修改应付表
            var arap = _arapApp.GetSingleBack(id);
            if (arap != null)
            {
                arap.FinanceNumber = financeNumber;
                _arapApp.Update(arap);
            }
            var obj = _purchaseApp.GetSinglePurchaseReconciliation(id);
            if (obj != null)
            {
                obj.FinanceNumber = financeNumber;
                _purchaseApp.UpdatePurchaseReconciliation(obj);
            }
            int count = _arapApp.GetCountFinanceNum(financeNumber);//插入发票号表
            if (count == 0)
            {
                FinanceNum fn = new FinanceNum();
                fn.Id = Guid.NewGuid();
                fn.FinanceNumber = financeNumber;
                fn.Type = 2;
                fn.Status = 1;
                _arapApp.InsertFinanceNum(fn);
            }

            return new { Code = 200 }.ToJson();
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string UpdateReconciliation(PurchaseReconciliation web)
        {
            var obj = _purchaseApp.GetSinglePurchaseReconciliation(web.Id);
            string financeNumber = "0";
            if (!string.IsNullOrEmpty(web.FinanceNumber) && web.FinanceNumber != "0")
            {
                financeNumber = web.FinanceNumber.Trim();
            }

            if (obj != null)
            {
                DateTime nowTime = DateTime.Now;

                obj.FinanceNumber = financeNumber;
                obj.Status = 1;
                obj.CreateTime = nowTime;
                obj.CreatorId = operatorModel.UserId;
                obj.CreatorName = operatorModel.FamilyName;
                obj.TotalMoney = web.TotalMoney;
                obj.ReconciliationType = web.ReconciliationType;
                _purchaseApp.UpdatePurchaseReconciliation(obj);

                PurchaseCompose pc = _purchaseApp.GetSinglePurchaseComposeById(obj.PurchaseComposeId);
                if (pc != null)
                {
                    pc.FinanceNumber = financeNumber;
                    _purchaseApp.UpdatePurchaseCompose(pc);
                }

                OperateRecord o = new OperateRecord();
                o.ItemId = web.Id;
                o.TypeId = 23;
                o.EndTime = nowTime;
                o.CreatorId = operatorModel.UserId;
                o.CreatorName = operatorModel.FamilyName;
                _operateRecordApp.UpdateOperateRecord(o);//修改本操作人员工作记录日志

                //插入应付账款表
                Arap arap = new Arap();
                Guid newId = Guid.NewGuid();
                arap.Id = newId;
                arap.Status = -1;
                arap.FinanceNumber = financeNumber;
                arap.PurchaseComposeId = obj.PurchaseComposeId;
                arap.FinanceInvoiceId = obj.Id;
                arap.OrderId = Guid.Empty;
                arap.ApplyTime = nowTime;
                arap.Type = 2;
                _arapApp.Add(arap);

                int count = _arapApp.GetCountFinanceNum(financeNumber);//插入发票号表
                if (count == 0)
                {
                    FinanceNum fn = new FinanceNum();
                    fn.Id = Guid.NewGuid();
                    fn.FinanceNumber = financeNumber;
                    fn.Type = 2;
                    fn.Status = -1;
                    _arapApp.InsertFinanceNum(fn);
                }

                //插入给下一个工作人员添加人工记录
                OperateRecord o1 = new OperateRecord();
                o1.Id = Guid.NewGuid();
                o1.ItemId = newId;//Id
                o1.TypeId = 24;
                o1.StartTime = nowTime;
                o1.EndTime = null;
                o1.CreatorId = null;
                _operateRecordApp.AddOperateRecord(o1);
            }
            return Result.ToJson();
        }


        public ActionResult PurchaseInfoLayout(Guid pcId)
        {
            PurchaseCompose pc = _purchaseApp.GetSinglePurchaseComposeById(pcId);
            Customer customer = _purchaseApp.GetSingleCustomer(2, pc.SupplierId.Value);

            Product pro = _technologyApp.GetSingleProduct(pc.ProductId);

            List<ProductTechnologyView> pvList = new List<ProductTechnologyView>();
            List<Relation> relationList = _technologyApp.GetListRelation(pc.Id, "PurchaseCompose-Purchase");
            foreach (var relation in relationList)
            {
                if (relation.SecondId != null)
                {
                    ProductTechnologyView pvObj = _technologyApp.GetRelationProductList(relation.SecondId.Value, pro.Id);
                    if (pvObj != null)
                    {
                        pvList.Add(pvObj);
                    }
                }
            }

            ViewBag.PvList = pvList;
            ViewBag.Product = pro;
            ViewBag.Customer = customer;
            ViewBag.OperationTime = pc.CreateTime == null ? "" : pc.CreateTime.Value.ToString("yyyy-MM-dd");//操作时间
            return View(pc);
        }

        /// <summary>
        /// 采购查看和确认采购页面
        /// </summary>
        /// <param name="pcId"></param>
        /// <returns></returns>
        public ActionResult PurchaseLookInfo(Guid pcId)
        {
            IEnumerable<Customer> customerList = _purchaseApp.GetCustomerList(2);
            PurchaseCompose pc = _purchaseApp.GetSinglePurchaseComposeById(pcId);
            Customer customer = new Customer();
            if (pc != null && pc.SupplierId != null)
            {
                customer = _purchaseApp.GetSingleCustomer(2, pc.SupplierId.Value);
            }
            else
            {
                //return RedirectToAction("PurQuery");
            }

            Product pro = _technologyApp.GetSingleProduct(pc.ProductId);
            Examine examine = _examineApp.GetSinglExamineByItemId(pcId);
            List<ProductTechnologyView> pvList = new List<ProductTechnologyView>();
            List<Relation> relationList = _technologyApp.GetListRelation(pc.Id, "PurchaseCompose-Purchase");
            foreach (var relation in relationList)
            {
                if (relation.SecondId != null)
                {
                    ProductTechnologyView pvObj = _technologyApp.GetRelationProductList(relation.SecondId.Value, pro.Id);
                    if (pvObj != null)
                    {
                        pvList.Add(pvObj);
                    }
                }
            }
            ViewBag.Examine = examine;
            ViewBag.PvList = pvList;
            ViewBag.Product = pro;
            ViewBag.Customer = customer;
            ViewBag.CustomerList = customerList;
            ViewBag.OperationTime = pc.CreateTime == null ? "" : pc.CreateTime.Value.ToString("yyyy-MM-dd");//操作时间
            return View(pc);
        }

        /// <summary>
        /// 采购合并打印
        /// </summary>
        /// <returns></returns>
        public ActionResult PurchasePrint(int page = 1, string supplierName = "")
        {
            ViewBag.SupplierName = supplierName.Trim();
            IPagedList<OrderView> ppList = _purchaseApp.GetListPurchasePrint(supplierName.Trim()).ToPagedList(page, 10);

            return View(ppList);
        }

        public ActionResult PurchaseInfoPrint(Guid id)
        {
            IEnumerable<NewProductView> newlist = _purchaseApp.GetListPurchasePrintSub(id);
            var purchasePrint = _purchaseApp.GetSinglePurchasePrintBack(id);
            Customer customer = null;
            if (purchasePrint != null)
            {
                customer = _purchaseApp.GetSingleCustomer(2, purchasePrint.SupplierId);
            }
            ViewBag.Customer = customer;
            ViewBag.PurchasePrintId = id;
            return View(newlist);
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string UpdatePurchaseInfoPrint(Guid pid)
        {
            var purchasePrint = _purchaseApp.GetSinglePurchasePrintBack(pid);
            purchasePrint.Status = 1;
            _purchaseApp.UpdatePurchasePrint(purchasePrint);
            return Result.ToJson();
        }

        /// <summary>
        /// 采购查看和确认采购页面
        /// </summary>
        /// <param name="pcId"></param>
        /// <returns></returns>
        public ActionResult PurchaseLookInfoLayout(Guid pcId)
        {
            PurchaseCompose pc = _purchaseApp.GetSinglePurchaseComposeById(pcId);
            Customer customer = _purchaseApp.GetSingleCustomer(2, pc.SupplierId.Value);

            Product pro = _technologyApp.GetSingleProduct(pc.ProductId);

            List<ProductTechnologyView> pvList = new List<ProductTechnologyView>();
            List<Relation> relationList = _technologyApp.GetListRelation(pc.Id, "PurchaseCompose-Purchase");
            foreach (var relation in relationList)
            {
                if (relation.SecondId != null)
                {
                    ProductTechnologyView pvObj = _technologyApp.GetRelationProductList(relation.SecondId.Value, pro.Id);
                    if (pvObj != null)
                    {
                        pvList.Add(pvObj);
                    }
                }
            }

            ViewBag.PvList = pvList;
            ViewBag.Product = pro;
            ViewBag.Customer = customer;
            ViewBag.OperationTime = pc.CreateTime == null ? "" : pc.CreateTime.Value.ToString("yyyy-MM-dd");//操作时间
            return View(pc);
        }

        ///// <summary>
        ///// 自定义采购（补单）
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult AddPurchase(Guid pcId, int type)
        //{
        //    IEnumerable<Customer> customerList = _purchaseApp.GetCustomerList(2);
        //    ViewBag.ProductList = _productApp.GetList(0, 1, "", "");
        //    PurchaseCompose pc = new PurchaseCompose();
        //    Product pro = new Product();
        //    Examine examine = null;
        //    //采购补单
        //    if (type == 3 && pcId != Guid.Empty)
        //    {
        //        examine = _examineApp.GetSinglExamineByItemId(pcId);
        //        pc = _purchaseApp.GetSinglePurchaseComposeById(pcId);
        //        decimal amount = pc.Amount;
        //        pro = _technologyApp.GetSingleProduct(pc.ProductId);
        //        if (pc != null)
        //        {
        //            decimal standardAmount = pc.StandardAmount;
        //            IEnumerable<PurchaseCompose> subList = _purchaseApp.GetSubListPurchaseComposeById(pcId);
        //            if (subList != null)
        //            {
        //                foreach (var item in subList)
        //                {
        //                    //可能没有质检
        //                    if (item.StandardAmount == 0)
        //                    {
        //                        standardAmount += item.Amount;
        //                    }
        //                }
        //            }
        //            pc.Amount = amount - standardAmount;
        //        }
        //    }

        //    ViewBag.Product = pro;

        //    #region 生成订单号
        //    string shortName = operatorModel.ShortName;
        //    string shortTime = GenerateId.GenerateyyyyMm();
        //    PurchaseCompose lastCompose = _createNewNumberApp.GetLastPurchaseCompose(shortName + "-" + shortTime);
        //    int lastNum = 1;
        //    if (lastCompose != null && lastCompose.Number.Split('-').Length == 3 && Validate.IsIntByParse(lastCompose.Number.Split('-')[2]))
        //    {
        //        lastNum = Convert.ToInt32(lastCompose.Number.Split('-')[2]) + 1;
        //    }
        //    string newNumber = shortName + "-" + GenerateId.GenerateOrderNumberBack() + "-" + lastNum.ToString().PadLeft(3, '0');//生成采购编号
        //    #endregion

        //    ViewBag.Examine = examine;
        //    ViewBag.Type = type;
        //    ViewBag.PurchaseNum = newNumber;//生成采购编号
        //    ViewBag.CustomerList = customerList;
        //    ViewBag.OperationName = operatorModel.FamilyName;//操作人
        //    ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间

        //    return View(pc);
        //}

        /// <summary>
        /// 添加采购单
        /// </summary>
        /// <param name="pcId"></param>
        /// <returns></returns>
        public ActionResult PurchaseInfo(Guid pcId)
        {
            IEnumerable<Customer> customerList = _purchaseApp.GetCustomerList(2);
            PurchaseCompose pc = _purchaseApp.GetSinglePurchaseComposeById(pcId);

            //OrderProduct op = _orderProductApp.GetSingleOrderProductBypurId(tId);
            //Order ord = _orderProductApp.GetSingleOrder(op.OrderId.Value);
            Product pro = _technologyApp.GetSingleProduct(pc.ProductId);
            //User u = _orderProductApp.GetSinleUserById(ord.UserId.Value);

            List<ProductTechnologyView> pvList = new List<ProductTechnologyView>();
            List<Relation> relationList = _technologyApp.GetListRelation(pc.Id, "PurchaseCompose-Purchase");
            List<WebTimeSort> timeList = new List<WebTimeSort>();
            DateTime timeEndTest = DateTime.Now.AddDays(1);


            foreach (var relation in relationList)
            {
                if (relation.SecondId != null)
                {
                    ProductTechnologyView pvObj = _technologyApp.GetRelationProductList(relation.SecondId.Value, pro.Id);
                    if (pvObj != null)
                    {
                        pvList.Add(pvObj);
                        bool timeflag = DateTime.TryParse(pvObj.SendTime, out timeEndTest);
                        if (timeflag)
                        {
                            timeList.Add(new WebTimeSort { Name = pvObj.OrderNum, SendTime = DateTime.Parse(pvObj.SendTime), Price = pvObj.Price });
                        }
                    }
                }
            }

            ViewBag.PvList = pvList;
            ViewBag.Product = pro;
            DateTime earliestTime = DateTime.Now;
            decimal price = 0;
            if (timeList.Count > 0)
            {
                var webTimeSort = timeList.OrderBy(a => a.SendTime).FirstOrDefault();
                if (webTimeSort != null)
                {
                    earliestTime = webTimeSort.SendTime;
                    //price = webTimeSort.Price;
                }
            }
            else
            {
                //price = pro.Price;
            }
            PurchaseCompose earPc = _purchaseApp.GetSingleEarlistPurchaseComposeBypId(pc.ProductId);
            if (earPc != null)
            {
                price = earPc.CostPrice;
            }
            else
            {
                price = pro.Price;
            }

            string checkInfoMemo = "";
            if (pvList.Count > 0)
            {
                var pvListLast = pvList.OrderBy(a => a.CreateTime);
                foreach (var item in pvListLast)
                {
                    OriginalCost oc = _originalCostApp.GetSingleOriginalCostByTid(item.TechnologyId);
                    if (oc != null && string.IsNullOrEmpty(oc.Memo))
                    {
                        checkInfoMemo = oc.Memo;
                    }
                }
            }

            ViewBag.CheckInfoMemo = checkInfoMemo;
            ViewBag.EarliestTime = earliestTime.ToString("yyyy-MM-dd");
            ViewBag.EarliestPrice = price;
            #region 生成订单号
            string shortName = operatorModel.FamilyName;
            string shortTime = GenerateId.GenerateyyyyMm();
            PurchaseCompose lastCompose = _createNewNumberApp.GetLastPurchaseCompose(shortName + "-" + shortTime);
            int lastNum = 1;
            if (lastCompose != null && lastCompose.Number.Split('-').Length == 3 && Validate.IsIntByParse(lastCompose.Number.Split('-')[2]))
            {
                lastNum = Convert.ToInt32(lastCompose.Number.Split('-')[2]) + 1;
            }
            string newNumber = shortName + "-" + GenerateId.GenerateOrderNumberBack() + "-" + lastNum.ToString().PadLeft(3, '0');//生成采购编号
            #endregion

            ViewBag.PurchaseNum = newNumber;
            ViewBag.CustomerList = customerList;
            ViewBag.OperationName = operatorModel.FamilyName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间
            return View(pc);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="web"></param>
        /// <param name="type">1.订单产品外购 2.自定义采购 3:采购补单</param>
        /// <param name="guids">选中的订单iD集合</param>
        /// <param name="amountReal">原始总数量</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        public string UpdatePurchase(PurchaseCompose web, int type, List<Guid> guids)
        {
            DateTime nowTime = DateTime.Now;
            web.CreatorId = operatorModel.UserId;
            web.CreatorName = operatorModel.FamilyName;
            web.CreateTime = nowTime;
            web.Status = 2;
            if (type == 1)
            {
                web.ApplyId = operatorModel.UserId;
                List<Relation> relationList = _technologyApp.GetListRelation(web.Id, "PurchaseCompose-Purchase");
                List<Relation> leave = relationList.Where(a => !guids.Contains(a.SecondId.Value)).ToList();//剩下没选中的PurchaseId集合
                //说明全部选中
                if (leave.Count == 0)
                {
                    _purchaseApp.UpdatePurchaseCompose(web); //修改采购单状态
                }
                else
                {
                    PurchaseCompose pc = _purchaseApp.GetSinglePurchaseComposeById(web.Id);
                    Guid orgPcId = web.Id;
                    decimal orgAmount = web.Amount;//已确认采购数量
                    decimal subAmount = pc.Amount - web.Amount;//剩下未采购的数量，放回原订单
                    web.Status = 1;
                    web.Amount = subAmount;
                    _purchaseApp.UpdatePurchaseCompose(web); //修改采购单状态


                    //添加新的采购单信息（已选购完的）
                    #region 生成订单号
                    string shortName = operatorModel.FamilyName;
                    string shortTime = GenerateId.GenerateyyyyMm();
                    PurchaseCompose lastCompose = _createNewNumberApp.GetLastPurchaseCompose(shortName + "-" + shortTime);
                    int lastNum = 1;
                    if (lastCompose != null && lastCompose.Number.Split('-').Length == 3 && Validate.IsIntByParse(lastCompose.Number.Split('-')[2]))
                    {
                        lastNum = Convert.ToInt32(lastCompose.Number.Split('-')[2]) + 1;
                    }
                    string newNumber = shortName + "-" + GenerateId.GenerateOrderNumberBack() + "-" + lastNum.ToString().PadLeft(3, '0');//生成采购编号
                    #endregion

                    PurchaseCompose newpc = pc;
                    Guid newId = Guid.NewGuid();
                    newpc.Id = newId;
                    newpc.Status = 2;
                    newpc.Amount = orgAmount;
                    newpc.Number = newNumber;
                    newpc.ArrivalAmount = 0;
                    newpc.ApplyTime = nowTime;
                    newpc.CreateTime = nowTime;
                    _purchaseApp.InsertPurchaseCompose(newpc);

                    //插入给下一个工作人员添加人工记录
                    OperateRecord o2 = new OperateRecord();
                    o2.Id = Guid.NewGuid();
                    o2.ItemId = newId;
                    o2.TypeId = 13;
                    o2.StartTime = nowTime;
                    o2.EndTime = null;
                    o2.CreatorId = operatorModel.UserId;
                    o2.CreatorName = operatorModel.FamilyName;
                    _operateRecordApp.AddOperateRecord(o2);

                    foreach (var itemId in guids)
                    {
                        Relation oldRelation = _technologyApp.GetSigleRelation(orgPcId, itemId, "PurchaseCompose-Purchase");
                        if (oldRelation != null)
                        {
                            oldRelation.FirstId = newId;
                            _technologyApp.UpdateRelation(oldRelation);
                        }
                        Relation oldrela = _technologyApp.GetSigleRelation(orgPcId, itemId, "PurchaseCompose-Order");
                        if (oldrela != null)
                        {
                            oldrela.FirstId = newId;
                            _technologyApp.UpdateRelation(oldrela);
                        }
                    }
                }

                /*#region 插入采购打印合并
                if (web.SupplierId != null)
                {
                    //插入采购打印合并
                    PurchasePrintSub ppSubtemp = _purchaseApp.GetSinglePurchasePrintSub(web.SupplierId.Value, web.ProductId, web.CostPrice, DateTime.Now.Date, DateTime.Now.Date.AddDays(1));
                    if (ppSubtemp != null)
                    {
                        ppSubtemp.Amount = ppSubtemp.Amount + web.Amount;
                        _purchaseApp.UpdatePurchasePrintSub(ppSubtemp);
                    }
                    else
                    {
                        PurchasePrint pptemp = _purchaseApp.GetSinglePurchasePrint(web.SupplierId.Value, DateTime.Now.Date, DateTime.Now.Date.AddDays(1));
                        if (pptemp != null)
                        {
                            PurchasePrintSub ppSub = new PurchasePrintSub();//子表
                            ppSub.Id = Guid.NewGuid();
                            ppSub.PurchasePrintId = pptemp.Id;
                            ppSub.SupplierId = web.SupplierId.Value;
                            ppSub.ProductId = web.ProductId;
                            ppSub.ProductName = web.ProductName;
                            ppSub.CreateTime = DateTime.Now;
                            ppSub.Amount = web.Amount;
                            ppSub.CostPrice = web.CostPrice;
                            ppSub.OtherId = web.Id;
                            ppSub.Status = 0;
                            _purchaseApp.AddPurchasePrintSub(ppSub);
                        }
                        else
                        {
                            PurchasePrint pp = new PurchasePrint();//主表
                            pp.Id = Guid.NewGuid();
                            pp.SupplierId = web.SupplierId.Value;
                            pp.ProductId = web.ProductId;
                            pp.ProductName = web.ProductName;
                            pp.CreateTime = DateTime.Now;
                            pp.Amount = web.Amount;
                            pp.Status = 0;
                            _purchaseApp.AddPurchasePrint(pp);

                            PurchasePrintSub ppSub = new PurchasePrintSub();//子表
                            ppSub.Id = Guid.NewGuid();
                            ppSub.PurchasePrintId = pp.Id;
                            ppSub.SupplierId = web.SupplierId.Value;
                            ppSub.ProductId = web.ProductId;
                            ppSub.ProductName = web.ProductName;
                            ppSub.CreateTime = DateTime.Now;
                            ppSub.Amount = web.Amount;
                            ppSub.CostPrice = web.CostPrice;
                            ppSub.OtherId = web.Id;
                            ppSub.Status = 0;
                            _purchaseApp.AddPurchasePrintSub(ppSub);
                        }
                    }
                }

                #endregion*/

            }
            if (type == 2 || type == 3)
            {
                web.ApplyTime = nowTime;
                Guid newId = Guid.NewGuid();
                web.Id = newId;
                web.ApplyId = operatorModel.UserId;
                web.Type = type;
                //自定义采购
                if (type == 2)
                {
                    web.ParentId = null;
                }
                _purchaseApp.InsertPurchaseCompose(web);//添加自定义采购单
                //补单
                if (type == 3 && web.ParentId != null)
                {
                    List<Relation> relationList = _technologyApp.GetListRelation(web.ParentId.Value, "PurchaseCompose-Purchase");
                    foreach (var item in relationList)
                    {
                        Relation re1 = new Relation();
                        re1.Id = Guid.NewGuid();
                        re1.TypeId = "PurchaseCompose-Purchase";
                        re1.FirstId = web.Id;
                        re1.SecondId = item.SecondId;
                        _technologyApp.InsertRelation(re1);
                    }
                    List<Relation> relationListo = _technologyApp.GetListRelation(web.ParentId.Value, "PurchaseCompose-Order");
                    foreach (var item in relationListo)
                    {
                        Relation re1 = new Relation();
                        re1.Id = Guid.NewGuid();
                        re1.TypeId = "PurchaseCompose-Order";
                        re1.FirstId = web.Id;
                        re1.SecondId = item.SecondId;
                        _technologyApp.InsertRelation(re1);
                    }
                }

                //插入给下一个工作人员添加人工记录
                OperateRecord o2 = new OperateRecord();
                o2.Id = Guid.NewGuid();
                o2.ItemId = newId;
                o2.TypeId = 13;
                o2.StartTime = nowTime;
                o2.EndTime = null;
                o2.CreatorId = operatorModel.UserId;
                o2.CreatorName = operatorModel.FamilyName;
                _operateRecordApp.AddOperateRecord(o2);
            }

            //插入给下一个工作人员添加人工记录（采购负责人审核）
            OperateRecord o1 = new OperateRecord();
            o1.Id = Guid.NewGuid();
            o1.ItemId = web.Id;//采购单Id
            o1.TypeId = 17;
            o1.StartTime = nowTime;
            o1.EndTime = null;
            o1.CreatorId = null;
            _operateRecordApp.AddOperateRecord(o1);

            return Result.ToJson();
        }


        [HttpPost]
        [HandlerAjaxOnly]
        public string CompletePurchase(PurchaseCompose web)
        {
            /*PurchaseCompose objCompose = _purchaseApp.GetSinglePurchaseComposeById(web.Id);
            //填写发票号
            if (objCompose.Status == 10 && string.IsNullOrEmpty(objCompose.FinanceNumber) && objCompose.ParentId == null)
            {
                objCompose.FinanceNumber = web.FinanceNumber;
                _purchaseApp.UpdatePurchaseCompose(objCompose);//修改采购单发票号
            }*/

            DateTime nowTime = DateTime.Now;
            if (web.ApplyId == Guid.Empty)
            {
                web.ApplyId = null;
            }
            web.CreatorId = operatorModel.UserId;
            web.CreatorName = operatorModel.FamilyName;
            web.CreateTime = nowTime;
            web.Status = 5;
            //return Result.ToJson();
            _purchaseApp.UpdatePurchaseCompose(web);//修改采购单状态

            List<Relation> relationList = _technologyApp.GetListRelation(web.Id, "PurchaseCompose-Purchase");
            foreach (var item in relationList)
            {
                if (item.SecondId != null)
                {
                    OrderProduct op = _orderProductApp.GetSingleOrderProductBypurId(item.SecondId.Value);
                    op.Progress = 9;
                    _orderProductApp.Update(op);
                }
            }

            OperateRecord o = new OperateRecord();
            o.ItemId = web.Id;
            o.TypeId = 13;
            o.EndTime = nowTime;
            o.CreatorId = operatorModel.UserId;
            o.CreatorName = operatorModel.FamilyName;
            _operateRecordApp.UpdateOperateRecord(o);//修改本操作人员工作记录日志

            Examine e = new Examine();//插入质检表
            Guid newId = Guid.NewGuid();
            e.Id = newId;
            e.Type = 1;
            e.ItemId = web.Id;//对应采购单
            e.ApplyTime = nowTime;
            e.CreatorId = null;
            e.CreateTime = null;
            e.Status = -1;
            e.ApplyId = operatorModel.UserId;
            _examineApp.Add(e);

            //插入给下一个工作人员添加人工记录（质检）
            OperateRecord o1 = new OperateRecord();
            o1.Id = Guid.NewGuid();
            o1.ItemId = newId;//工单id
            o1.TypeId = 15;
            o1.StartTime = nowTime;
            o1.EndTime = null;
            o1.CreatorId = null;
            _operateRecordApp.AddOperateRecord(o1);

            return Result.ToJson();
        }

        /// <summary>
        /// 判断该采购单是否可以再补单
        /// </summary>
        /// <param name="pcId"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        public string VerifyPurchase(Guid pcId)
        {
            Result.Status = "2";
            PurchaseCompose p = _purchaseApp.GetSinglePurchaseComposeById(pcId);
            if (p != null)
            {
                decimal amount = p.StandardAmount;
                IEnumerable<PurchaseCompose> subList = _purchaseApp.GetSubListPurchaseComposeById(pcId);
                if (subList != null)
                {
                    foreach (var item in subList)
                    {
                        //可能没有质检
                        if (item.StandardAmount == 0)
                        {
                            amount += item.Amount;
                        }
                    }
                }
                if (p.Amount > amount)//申请数量>总补单数量和本身合格数量
                {
                    Result.Status = "1";
                }
            }
            return Result.ToJson();
        }


        /// <summary>
        /// 添加自定义采购单
        /// </summary>
        /// <param name="web"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        public string AddCompletePurchase(Purchase web)
        {


            return Result.ToJson();
        }

        public ActionResult EditPurchase()
        {
            return View();
        }

        public ActionResult Check(int page = 1, string productName = "", string productNum = "", string technologyNum = "")
        {
            productName = productName.Trim();
            productNum = productNum.Trim();
            technologyNum = technologyNum.Trim();
            ViewBag.ProductName = productName;
            ViewBag.ProductNum = productNum;
            ViewBag.TechnologyNum = technologyNum;
            IPagedList<ProductTechnologyView> tecjList = _originalCostApp.GetList(-1, productName, productNum, technologyNum).ToPagedList(page, 10);
            return View(tecjList);
        }

        public ActionResult QueryOrder(int page = 1, string productName = "", string productNum = "", string technologyNum = "")
        {
            productName = productName.Trim();
            productNum = productNum.Trim();
            technologyNum = technologyNum.Trim();
            ViewBag.ProductName = productName;
            ViewBag.ProductNum = productNum;
            ViewBag.TechnologyNum = technologyNum;
            IPagedList<ProductTechnologyView> tecjList = _originalCostApp.GetList(1, productName, productNum, technologyNum).ToPagedList(page, 10);
            return View(tecjList);
        }

        public ActionResult LookInfo(Guid tId)
        {
            OriginalCost oc = _originalCostApp.GetSingleOriginalCost(tId);
            ViewBag.Data = oc.Data;
            ViewBag.technologyId = oc.TechnologytId;
            Technology t = _technologyApp.GetSingleTechnology(oc.TechnologytId);
            OrderProduct op = _orderProductApp.GetSingleOrderProduct(t.OrderProductId);
            Product p = _technologyApp.GetSingleProduct(op.ProductId.Value);
            //ProductTechnologyView firstMaterial = _technologyApp.GetFirstItem(t.Id);//主料
            //ViewBag.ProductTechnologyView = firstMaterial;
            ViewBag.ProductName = p.Name;
            return View(oc);
        }

        public ActionResult CheckInfo(Guid tId)
        {
            OriginalCost oc = _originalCostApp.GetSingleOriginalCost(tId);
            Technology t = _technologyApp.GetSingleTechnology(oc.TechnologytId);
            OrderProduct op = _orderProductApp.GetSingleOrderProduct(t.OrderProductId);
            Product p = _technologyApp.GetSingleProduct(op.ProductId.Value);
            ViewBag.OrderProductId = t.OrderProductId;
            ViewBag.TechnologyCreatorName = t.CreatorName;
            ViewBag.ProductName = p.Name;
            //IEnumerable<ProductTechnologyView> listView = _technologyApp.GetListItem("", "", t.Id);
            ProductTechnologyView firstMaterial = _technologyApp.GetFirstItem(t.Id);//主料
            List<ProductTechnologyView> technologyItem = _technologyApp.GetTechnologyItems(t.Id);//辅料
            //List<MaterialsList> list = new List<MaterialsList>();
            //if (oc != null && !string.IsNullOrEmpty(oc.Materials))
            //{
            //    List<string> strlist = oc.Materials.Split(',').ToList();
            //    for (int i = 0; i < strlist.Count; i++)
            //    {
            //        MaterialsList m = new MaterialsList();
            //        Product pro = _technologyApp.GetSingleProduct(new Guid(strlist[i]));
            //        m.Name = pro.Name;
            //        m.Id = strlist[i];
            //        list.Add(m);
            //    }
            //}

            //主料成本预算
            if (t.DistributeType == 1)
            {
                //firstMaterial.Price = (t.GiveH * t.GiveW * firstMaterial.Price) / 1000;
            }
            else
            {
                firstMaterial.Price = p.Price * op.Amount;
            }

            ViewBag.DistributeType = t.DistributeType;
            ViewBag.TechnologyItemList = technologyItem;
            ViewBag.ProductTechnologyView = firstMaterial;
            ViewBag.OperationName = operatorModel.FamilyName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间

            return View(oc);
        }


        [HttpPost]
        [HandlerAjaxOnly]
        public string UpdateOriginalCost(Guid id, string data, string memo)
        {
            OriginalCost oc = _originalCostApp.GetSingleOriginalCost(id);
            if (oc != null)
            {
                oc.Data = data;
                oc.Memo = memo;
                _originalCostApp.AddOrUpdate(oc);//修改原料成本核算表
                return new { Code = 200 }.ToJson();
            }
            return new { Code = -200 }.ToJson();
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string AddCheck(OriginalCost web, Guid orderProductId, string technologyCn)
        {
            OriginalCost oc = _originalCostApp.GetSingleOriginalCost(web.Id);
            OrderProduct op = _orderProductApp.GetSingleOrderProduct(orderProductId);//根据工艺订单id查找关系表对应的OrderId
            if (oc == null)
            {
                Result.Status = "error";
                Result.Message = "数据不存在";
                return Result.ToJson();
            }
            if (op == null || op.OrderId == null)
            {
                Result.Status = "error";
                Result.Message = "数据不存在001";
                return Result.ToJson();
            }
            DateTime nowTime = DateTime.Now;
            oc.Data = web.Data;
            oc.CreatorID = operatorModel.UserId;
            oc.CreatorName = operatorModel.FamilyName;
            oc.CreateTime = nowTime;
            oc.Status = 1;
            oc.Memo = web.Memo;
            var resu = _originalCostApp.AddOrUpdate(oc);//修改原料成本核算表

            OperateRecord o = new OperateRecord();
            o.ItemId = oc.Id;
            o.TypeId = 5;
            o.EndTime = nowTime;
            o.CreatorId = operatorModel.UserId;
            o.CreatorName = operatorModel.FamilyName;
            _operateRecordApp.UpdateOperateRecord(o);//修改本操作人员工作记录日志


            int count = _orderProductApp.GetCheckOrderProductByOrderId(op.OrderId.Value);//如果订单旗下所有工艺都审核完毕才修改订单状态
            if (count == 0)//==0
            {
                _operateRecordApp.UpdateOrderStateById(op.OrderId.Value, 4);//更改订单Status=4
            }
            FinanceCost fc = new FinanceCost();//给财务生成数据对应Order表的主键
            Guid fcnewId = Guid.NewGuid();
            fc.Id = fcnewId;
            fc.OrderId = op.OrderId.Value;
            fc.OrderProductId = orderProductId;
            fc.Status = -1;
            fc.CreateTime = nowTime;//默认插入防止为空
            fc.ApplyTime = nowTime;
            fc.OriginalPeople = operatorModel.FamilyName;
            fc.TechnologyPeople = technologyCn;//工艺操作人员名称
            fc.CreatorId = null;
            _financeCostApp.Add(fc);

            op.Progress = 3;
            _orderProductApp.Update(op);

            //插入给下一个工作人员添加人工记录（原料成本核算）
            OperateRecord o1 = new OperateRecord();
            o1.Id = Guid.NewGuid();
            o1.ItemId = fcnewId;//财务id
            o1.TypeId = 7;
            o1.StartTime = nowTime;
            o1.EndTime = null;
            o1.CreatorId = null;
            _operateRecordApp.AddOperateRecord(o1);//修改本操作人员工作记录日志

            return Result.ToJson();

        }

        public JsonResult InToPurchaseCompose(Guid opid, Guid purid, decimal amount)
        {
            int res = 0;
            OrderProduct op = _orderProductApp.GetSingleOrderProduct(opid);
            Purchase pur = _purchaseApp.GetSingle(purid);
            if (op != null && pur != null)
            {
                //说明是有的采购有的生产
                if (op.Amount > amount)
                {
                    Guid oriopId = op.Id;
                    //插入新 OrderProduct 和 Purchase
                    Guid newOpId = Guid.NewGuid();
                    Guid newPurId = Guid.NewGuid();
                    decimal sAmount = op.Amount - amount;//剩余未分配数量
                    OrderProduct newOp = op;
                    newOp.Id = newOpId;
                    newOp.Amount = sAmount;
                    newOp.PurchaseId = newPurId;
                    if (op.PrimaryID == null)
                    {
                        //用于查找上级的工艺详情
                        newOp.PrimaryID = oriopId;
                    }
                    _orderProductApp.Add(newOp);

                    Purchase newPur = pur;
                    newPur.Id = newPurId;
                    newPur.Status = 1;
                    newPur.Type = 1;
                    newPur.Amount = sAmount;
                    _purchaseApp.Add(newPur);

                    //处理原有数据（修改purchase和orderProduct的数量）
                    pur = _purchaseApp.GetSingle(purid);
                    pur.Status = 6;
                    pur.Amount = amount;
                    pur.CreateTime = DateTime.Now;
                    pur.ApplyTime = DateTime.Now;
                    pur.CreatorId = operatorModel.UserId;
                    pur.CreatorName = operatorModel.FamilyName;
                    _purchaseApp.Update(pur);

                    op = _orderProductApp.GetSingleOrderProduct(opid);
                    op.Type = 1;
                    op.Progress = 8;
                    op.Amount = amount;
                    _orderProductApp.Update(op);

                }
                if (op.Amount == amount)
                {
                    pur.Status = 6;
                    pur.CreateTime = DateTime.Now;
                    pur.CreatorId = operatorModel.UserId;
                    pur.CreatorName = operatorModel.FamilyName;
                    _purchaseApp.Update(pur);

                    op.Progress = 8;
                    op.Type = 1;
                    _orderProductApp.Update(op);
                }
            }
            return Json(res);
        }


        /// <summary>
        /// 还原重新分配
        /// </summary>
        /// <param name="opid"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public JsonResult PurchaseRestore(Guid opid, Guid pid)
        {
            Purchase pur = _purchaseApp.GetSingle(pid);
            OrderProduct op = _orderProductApp.GetSingleOrderProduct(opid);
            if (pur == null || op == null)
            {
                return Json(-1);
            }
            op.WorksheetId = null;
            op.Progress = 0;
            op.Type = 0;
            op.Status = 0;
            _orderProductApp.Update(op);

            pur.Status = 1;
            _purchaseApp.Update(pur);

            return Json(0);
        }

        /// <summary>
        /// 合并采购单
        /// </summary>
        /// <param name="opid"></param>
        /// <param name="purid"></param>
        /// <param name="type">1:合并  2：单独采购</param>
        /// <returns></returns>
        public JsonResult ToPurchase(Guid opid, Guid purid, int type)
        {
            int res = 0;
            OrderProduct op = _orderProductApp.GetSingleOrderProduct(opid);
            Purchase pur = _purchaseApp.GetSingle(purid);
            if (op != null && op.ProductId != null)
            {
                if (type == 1)
                {
                    pur.Status = 7;
                    _purchaseApp.Update(pur);

                    PurchaseCompose purchaseCompose = _purchaseApp.GetSinglePurchaseCompose(1, op.ProductId.Value, 1);

                    //说明可以把相同产品采购数量合并一起
                    if (purchaseCompose != null)
                    {
                        purchaseCompose.Amount += pur.Amount;
                        _purchaseApp.UpdatePurchaseCompose(purchaseCompose); //修改总数量

                        Relation re = new Relation();
                        re.Id = Guid.NewGuid();
                        re.TypeId = "PurchaseCompose-Purchase";
                        re.FirstId = purchaseCompose.Id;
                        re.SecondId = purid;
                        _technologyApp.InsertRelation(re);

                        Relation re1 = new Relation();
                        re1.Id = Guid.NewGuid();
                        re1.TypeId = "PurchaseCompose-Order";
                        re1.FirstId = purchaseCompose.Id;
                        re1.SecondId = op.OrderId;
                        _technologyApp.InsertRelation(re1);
                    }
                    else
                    {
                        DateTime nowTime = DateTime.Now;
                        PurchaseCompose pc = new PurchaseCompose();
                        Guid newId = Guid.NewGuid();
                        pc.Id = newId;
                        pc.ProductId = op.ProductId.Value;
                        pc.Status = 1;
                        pc.Type = 1;
                        pc.ApplyTime = nowTime;
                        pc.Amount = pur.Amount;
                        pc.PurchaseType = 1;
                        _purchaseApp.InsertPurchaseCompose(pc);


                        Relation re = new Relation();
                        re.Id = Guid.NewGuid();
                        re.TypeId = "PurchaseCompose-Purchase";
                        re.FirstId = newId;
                        re.SecondId = purid;
                        _technologyApp.InsertRelation(re);

                        Relation re1 = new Relation();
                        re1.Id = Guid.NewGuid();
                        re1.TypeId = "PurchaseCompose-Order";
                        re1.FirstId = newId;
                        re1.SecondId = op.OrderId;
                        _technologyApp.InsertRelation(re1);

                        //操作记录
                        OperateRecord o2 = new OperateRecord();
                        o2.Id = Guid.NewGuid();
                        o2.ItemId = newId;
                        o2.TypeId = 13;
                        o2.StartTime = nowTime;
                        o2.EndTime = null;
                        o2.CreatorId = null;
                        o2.CreatorName = null;
                        _operateRecordApp.AddOperateRecord(o2);
                    }
                }
                if (type == 2)
                {
                    pur.Status = 8;
                    _purchaseApp.Update(pur);

                    DateTime nowTime = DateTime.Now;
                    PurchaseCompose pc = new PurchaseCompose();
                    Guid newId = Guid.NewGuid();
                    pc.Id = newId;
                    pc.ProductId = op.ProductId.Value;
                    pc.Status = 1;
                    pc.Type = 1;
                    pc.ApplyTime = nowTime;
                    pc.Amount = pur.Amount;
                    pc.PurchaseType = 2;
                    _purchaseApp.InsertPurchaseCompose(pc);


                    Relation re = new Relation();
                    re.Id = Guid.NewGuid();
                    re.TypeId = "PurchaseCompose-Purchase";
                    re.FirstId = newId;
                    re.SecondId = purid;
                    _technologyApp.InsertRelation(re);

                    Relation re1 = new Relation();
                    re1.Id = Guid.NewGuid();
                    re1.TypeId = "PurchaseCompose-Order";
                    re1.FirstId = newId;
                    re1.SecondId = op.OrderId;
                    _technologyApp.InsertRelation(re1);

                    //操作记录
                    OperateRecord o2 = new OperateRecord();
                    o2.Id = Guid.NewGuid();
                    o2.ItemId = newId;
                    o2.TypeId = 13;
                    o2.StartTime = nowTime;
                    o2.EndTime = null;
                    o2.CreatorId = null;
                    o2.CreatorName = null;
                    _operateRecordApp.AddOperateRecord(o2);
                }
            }
            else
            {
                res = -1;
            }

            return Json(res);
        }

        public JsonResult ToWork(string opid, string purid, decimal amount)
        {
            int res = 0;
            Guid oderpid = new Guid(opid);
            Guid purchaseid = new Guid(purid);
            OrderProduct op = _orderProductApp.GetSingleOrderProduct(oderpid);
            Purchase pur = _purchaseApp.GetSingle(purchaseid);
            DateTime nowTime = DateTime.Now;
            Guid tmpId = Guid.NewGuid();
            //说明是有的采购有的生产
            if (op.Amount > amount)
            {
                Guid oriopId = op.Id;//原始工艺Id
                //插入新 OrderProduct 和 Purchase
                Guid newOpId = Guid.NewGuid();
                Guid newPurId = Guid.NewGuid();
                decimal sAmount = op.Amount - amount;//剩余未分配数量
                OrderProduct newOp = op;
                newOp.Id = newOpId;
                newOp.Amount = sAmount;
                newOp.PurchaseId = newPurId;
                newOp.WorksheetId = Guid.Empty;
                if (op.PrimaryID == null)
                {
                    //用于查找上级的工艺详情
                    newOp.PrimaryID = oriopId;
                }
                _orderProductApp.Add(newOp);

                Purchase newPur = pur;
                newPur.Id = newPurId;
                newPur.Status = 1;
                newPur.Type = 1;
                newPur.Amount = sAmount;
                _purchaseApp.Add(newPur);


                //处理原有数据（修改purchase和orderProduct的数量）
                pur = _purchaseApp.GetSingle(purchaseid);
                pur.Status = -1;
                pur.Amount = amount;
                pur.CreateTime = DateTime.Now;
                pur.ApplyTime = DateTime.Now;
                pur.CreatorId = operatorModel.UserId;
                pur.CreatorName = operatorModel.FamilyName;
                _purchaseApp.Update(pur);

                op = _orderProductApp.GetSingleOrderProduct(oderpid);
                op.Amount = amount;
                op.WorksheetId = tmpId;
                op.Progress = 7;
                op.Type = 2;
                _orderProductApp.Update(op);

            }
            if (op.Amount == amount)
            {
                op.WorksheetId = tmpId;
                op.Type = 2;
                op.Progress = 7;
                _orderProductApp.Update(op);

                pur.Status = -1;
                _purchaseApp.Update(pur);
            }
            Worksheet ws = new Worksheet();
            ws.Id = tmpId;
            ws.Status = -1;
            ws.ApplyTime = nowTime;
            ws.ProductId = op.ProductId.Value;
            ws.OtherId = op.OrderId;
            _worksheetApp.Add(ws);

            Relation re1 = new Relation();
            re1.Id = Guid.NewGuid();
            re1.TypeId = "Worksheet-Order";
            re1.FirstId = tmpId;
            re1.SecondId = op.OrderId;
            _technologyApp.InsertRelation(re1);

            //插入给下一个工作人员添加人工记录（加工单）
            OperateRecord o1 = new OperateRecord();
            o1.Id = Guid.NewGuid();
            o1.ItemId = tmpId;//加工单Id
            o1.TypeId = 11;
            o1.StartTime = nowTime;
            o1.EndTime = null;
            o1.CreatorId = null;
            _operateRecordApp.AddOperateRecord(o1);

            return Json(res);
        }



    }
}